package com.ym.wcp.framework.utils;

import com.google.common.base.CaseFormat;
import com.google.common.collect.Maps;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.beans.BeanGenerator;
import org.springframework.cglib.beans.BeanMap;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DynamicBeanUtil {

    public static Logger logger = LoggerFactory.getLogger(DynamicBeanUtil.class);

    public static Object getTarget(Object target, Map<String, String[]> addProperties) {
        PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
        PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(target);
        Map<String, Class> propertyMap = Maps.newHashMap();
        for (PropertyDescriptor d : descriptors) {
            if (!"class".equalsIgnoreCase(d.getName())) {
                propertyMap.put(d.getName(), d.getPropertyType());
            }
        }
        addProperties.forEach((k, v) -> propertyMap.put(k, v[0].getClass()));
        DynamicBean dynamicBean = new DynamicBean<>(target, propertyMap);
        propertyMap.forEach((k, v) -> {
            try {
                if (!addProperties.containsKey(k)) {
                    dynamicBean.setValue(k, propertyUtilsBean.getNestedProperty(target, k));
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        });
        addProperties.forEach((k, v) -> {
            try {
                Class aClass = propertyMap.get(k);
                if (aClass == String.class) {
                    dynamicBean.setValue(k, v[0]);
                }
                if (aClass == Integer.class) {
                    dynamicBean.setValue(k, Integer.parseInt(v[0]));
                }
                if (aClass == Long.class) {
                    dynamicBean.setValue(k, Long.parseLong(v[0]));
                }
                if (aClass == Double.class) {
                    dynamicBean.setValue(k, Double.parseDouble(v[0]));
                }
                if (aClass == Boolean.class) {
                    dynamicBean.setValue(k, Boolean.parseBoolean(v[0]));
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        });
        return dynamicBean.getTarget();
    }


    public static <T> T dynamicTarget(T target, Map<String, Object> addProperties, Class<T> cls) {
        PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
        PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(target);
        Map<String, Class> propertyMap = Maps.newHashMap();
        for (PropertyDescriptor d : descriptors) {
            if (!"class".equalsIgnoreCase(d.getName())) {
                propertyMap.put(d.getName(), d.getPropertyType());
            }
        }
        addProperties.forEach((k, v) -> propertyMap.put(k, v.getClass()));
        DynamicBean<T> dynamicBean = new DynamicBean<>(target, propertyMap);
        propertyMap.forEach((k, v) -> {
            try {
                if (!addProperties.containsKey(k)) {
                    dynamicBean.setValue(k, propertyUtilsBean.getNestedProperty(target, k));
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        });
        addProperties.forEach((k, v) -> {
            try {
                Class aClass = propertyMap.get(k);
                if (aClass == String.class) {
                    dynamicBean.setValue(k, v);
                }
                if (aClass == Integer.class) {
                    dynamicBean.setValue(k, Integer.parseInt(v.toString()));
                }
                if (aClass == Long.class) {
                    dynamicBean.setValue(k, Long.parseLong(v.toString()));
                }
                if (aClass == Double.class) {
                    dynamicBean.setValue(k, Double.parseDouble(v.toString()));
                }
                if (aClass == Boolean.class) {
                    dynamicBean.setValue(k, Boolean.parseBoolean(v.toString()));
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        });
        return dynamicBean.getTarget();
    }

    public static <T> T getFieldValueByName(String name, Object o, Class<T> cls) {
        try {
            //通过反射获取值
            Class<?> aClass = o.getClass();
            Method method;
            if (!name.contains("get")) {
                String methodName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "get_" + transFor(name));
                method = aClass.getMethod(methodName);
            } else {
                method = aClass.getMethod(name);
            }
            return (T) method.invoke(o);
        } catch (Exception ignored) {
        }
        return null;
    }

    public static <T> T getFieldValueByName(String name, T o) {
        try {
            //通过反射获取值
            Class<?> aClass = o.getClass();
            Method method;
            if (!name.contains("get")) {
                String methodName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "get_" + transFor(name));
                method = aClass.getMethod(methodName);
            } else {
                method = aClass.getMethod(name);
            }
            return (T) method.invoke(o);
        } catch (Exception ignored) {
        }
        return null;
    }

    private static class DynamicBean<T> {
        /**
         * 目标对象
         */
        private final T target;

        /**
         * 属性集合
         */
        private final BeanMap beanMap;

        public DynamicBean(T bean, Map<String, Class> propertyMap) {
            this.target = generateBean(bean.getClass(), propertyMap);
            this.beanMap = BeanMap.create(this.target);
        }

        /**
         * bean 添加属性和值
         *
         * @param property
         * @param value
         */
        public void setValue(String property, Object value) {
            beanMap.put(property, value);
        }

        /**
         * 获取属性值
         *
         * @param property
         * @return
         */
        public Object getValue(String property) {
            return beanMap.get(property);
        }

        /**
         * 获取对象
         *
         * @return
         */
        public T getTarget() {
            return this.target;
        }


        /**
         * 根据属性生成对象
         *
         * @param superclass
         * @param propertyMap
         * @return
         */
        private T generateBean(Class superclass, Map<String, Class> propertyMap) {
            BeanGenerator generator = new BeanGenerator();
            if (null != superclass) {
                generator.setSuperclass(superclass);
            }
            BeanGenerator.addProperties(generator, propertyMap);
            return (T) generator.create();
        }
    }

    private static String transFor(String name) {
        Matcher matcher = Pattern.compile("[A-Z]").matcher(name);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}